//
//  WKLoginViewController.m
//  WeKeTang
//
//  Created by ichina on 2017/8/22.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKLoginViewController.h"
#import "WKNavgationController.h"
#import "WKHomeViewController.h"
#import "WKDownLoadViewController.h"
#import "WKForgetPasswordController.h"
#import "WKProfireViewController.h"
#import "WKVerifyPhoneViewController.h"
#import "WKRegistViewController.h"
#import "WKBindingViewController.h"
#import <AFNetworking.h>
#import "UIDevice+KZExtension.h"
#import "NSString+KZExtension.h"
#import "WKLoginHandel.h"
#import "WKAlerView.h"
#import "WKUniversal.h"
#import "WXApiObject.h"
#import "WXApi.h"
#import "WKNetworkTools.h"
#import "AppDelegate.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
@interface WKLoginViewController ()<TencentSessionDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *ImgLogoView;
@property (weak, nonatomic) IBOutlet UITextField *TFPhoneNum;
@property (weak, nonatomic) IBOutlet UITextField *TFPassword;
@property (weak, nonatomic) IBOutlet UIButton *BtnLogin;
@property (nonatomic, strong)        UIButton *btnTourists;//访客登录
@property (weak, nonatomic) IBOutlet UILabel *weixinLabel;
@property (nonatomic, strong)        UILabel *labelTourists;
@property (weak, nonatomic) IBOutlet UILabel *remberLabel;
@property (weak, nonatomic) IBOutlet UILabel *labelQQ;
@property (weak, nonatomic) IBOutlet UIView *leftView;
@property (weak, nonatomic) IBOutlet UIView *rightView;

@property (weak, nonatomic) IBOutlet UIButton *BtnForgetPsd;
@property (weak, nonatomic) IBOutlet UIButton *BtnRegist;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tfPhoneConstan;
@property (nonatomic, strong) TencentOAuth *tencentOAuth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoViewConstan;
@property (weak, nonatomic) IBOutlet UIButton *BtnQQ;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *BtnQQConstan;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *BtnQQTopConstan;
@property (weak, nonatomic) IBOutlet UIButton *BtnWeChat;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *BtnWeChatConstan;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *BtnWeChatTopConstan;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftLineConstan;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightLineConstan;
@property (nonatomic, strong) WKAlerView *alertView;
@property (nonatomic, assign) NSInteger reachabilityStatus;
@property (nonatomic, copy) NSString *SESSID;

@property (nonatomic, assign) BOOL isOnLine;

@end

@implementation WKLoginViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self setupUI];
    [self loadData];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#fafafa"];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillHiden:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(weChatLoginSuccess:) name:@"WXLoginSuccess" object:nil];
   
    [[AppDelegate shareDelegate] addObserver:self forKeyPath:@"reachabilityStatus" options:0 context:NULL];
}
#pragma mark - 获取审核接口
- (void)loadData{
    __weak typeof(self) weakSelf = self;
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    //先获取当前的版本号
    NSString *version =[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    //再读区本地存储的版本好
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"featureswitch" forKey:@"commandid"];
    [para setObject:version forKey:@"version"];
    [[WKNetworkTools shareManger]RunNoneRequest:para path:kServerDomain tip:@"" completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *head = dict[@"head"];
        NSString *statuscode = head[@"statuscode"];
        if ([statuscode intValue] == 100) {
            _isOnLine = YES;
            weakSelf.btnTourists.hidden = NO;
            weakSelf.labelTourists.hidden = NO;
            weakSelf.BtnQQ.frame = CGRectMake(40, CGRectGetMaxY(weakSelf.remberLabel.frame)+10, 70, 70);
            weakSelf.labelQQ.frame = CGRectMake(40, CGRectGetMaxY(weakSelf.BtnQQ.frame)+5, 70, 21);
            weakSelf.BtnWeChat.frame = CGRectMake(kDeviceScreenWidth-40-70, CGRectGetMaxY(weakSelf.remberLabel.frame)+10, 70, 70);
            weakSelf.weixinLabel.frame = CGRectMake(kDeviceScreenWidth-40-70, CGRectGetMaxY(weakSelf.BtnWeChat.frame)+5, 70, 21);
            weakSelf.btnTourists.frame = CGRectMake(((kDeviceScreenWidth - 40*2-70*2)-70)*0.5+40+70, weakSelf.BtnQQ.top, 70, 70);
            weakSelf.labelTourists.frame = CGRectMake(((kDeviceScreenWidth - 40*2-70*2)-70)*0.5+40+70, CGRectGetMaxY(weakSelf.btnTourists.frame)+5, 70, 21);
        }else{
            _isOnLine = NO;
            weakSelf.remberLabel.text = @"第三方登录";
            weakSelf.BtnQQ.frame = CGRectMake(80, CGRectGetMaxY(weakSelf.remberLabel.frame)+15, 70, 70);
            weakSelf.labelQQ.frame = CGRectMake(80, CGRectGetMaxY(weakSelf.BtnQQ.frame)+15, 70, 21);
            weakSelf.btnTourists.hidden = YES;
            weakSelf.labelTourists.hidden = YES;
            weakSelf.BtnWeChat.frame = CGRectMake(kDeviceScreenWidth-80-70, CGRectGetMaxY(weakSelf.remberLabel.frame)+15, 70, 70);
            weakSelf.weixinLabel.frame = CGRectMake(kDeviceScreenWidth-80-70, CGRectGetMaxY(weakSelf.BtnWeChat.frame)+15, 70, 21);
        }
        NSLog(@"审核接口:%@",dict);
    }];
    
}
- (void)setupUI{
    
    self.navgationBar.hidden = YES;
    [self.BtnRegist setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
    UIView *leftView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView1.contentMode = UIViewContentModeCenter;
    self.TFPhoneNum.leftView = leftView1;
    self.TFPhoneNum.leftViewMode = UITextFieldViewModeAlways;
    self.TFPhoneNum.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFPhoneNum.layer.borderWidth = 1;
    [self.TFPhoneNum setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    
    UIView *leftView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView2.contentMode = UIViewContentModeCenter;
    self.TFPassword.leftView = leftView2;
    self.TFPassword.leftViewMode = UITextFieldViewModeAlways;
    self.TFPassword.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFPassword.layer.borderWidth = 1;
    [self.TFPassword setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    
    self.TFPhoneNum.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.TFPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    _tencentOAuth=[[TencentOAuth alloc]initWithAppId:kQQAppID andDelegate:self];
    
    if (_isReset) {
        self.TFPhoneNum.text = self.account;
        self.TFPassword.text = self.psd;
    }
    self.btnTourists = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.btnTourists setImage:IMG(@"icon_remberlogin.png") forState:UIControlStateNormal];
    [self.btnTourists addTarget:self action:@selector(btnTouristsAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnTourists];
    self.labelTourists = [[UILabel alloc]init];
    self.labelTourists.textColor = [UIColor colorWithHexString:@"#999999"];
    self.labelTourists.font = [UIFont systemFontOfSize:14];
    self.labelTourists.textAlignment = NSTextAlignmentCenter;
    self.labelTourists.text = @"游客登录";
    [self.view addSubview:self.labelTourists];
    if (![ WXApi  isWXAppInstalled ]  && ![ WXApi  isWXAppSupportApi ]){
        self.BtnWeChat.hidden = YES;
        self.weixinLabel.hidden = YES;
        self.BtnQQ.hidden = YES;
        self.labelQQ.hidden = YES;
    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"reachabilityStatus"]) {
        
        _reachabilityStatus = [AppDelegate shareDelegate].reachabilityStatus;
        NSLog(@" 当前网络状态:%ld",_reachabilityStatus);
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    // 返回你所需要的状态栏样式
    return UIStatusBarStyleLightContent;
}
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context{
    
    if ([keyPath isEqualToString:@"reachabilityStatus"]) {
        
        _reachabilityStatus = [AppDelegate shareDelegate].reachabilityStatus;
        NSLog(@" 当前网络状态:%ld",_reachabilityStatus);
    }
    
}
#pragma mark - 游客登录
- (void)btnTouristsAction{
    __weak typeof(self) weakSelf = self;
    NSDate *date = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMddhhmmss"];
    NSString *timestamp = [dateformatter stringFromDate:date];
    
    NSString *deviceID = mydeviceUniqueIdentifier();
    NSString *version =[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSString *mac= [WKUniversal macaddress];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"13004798971" forKey:@"account"];
    [para setObject:@"666666" forKey:@"password"];
    [para setObject:timestamp   forKey:@"timestamp"];
    [para setObject:@"1" forKey:@"sequenceid"];
    [para setObject:@"login" forKey:@"commandid"];
    [para setObject:version forKey:@"version"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:deviceID forKey:@"deviceid"];
    NSLog(@"登录mac：%@",mac);
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"登录中..." completionHandler:^(id responseObject) {
    } errorHandler:^(NSError *error) {
        [weakSelf showCustomAlertMessage:@"登录失败"];
        
    } finishHandler:^(id responseObject) {
        NSArray * cookieArr = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];//获取cookie
        for (NSHTTPCookie * cookie in cookieArr) {          //遍历cookie
            if ([cookie.name isEqualToString:@"PHPSESSID"]) {
                self.SESSID = cookie.value;
            }
        }
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *dicBody = dict[@"body"];
        NSDictionary *dicHead = dict[@"head"];
        NSLog(@"游客登录：%@",dict);
        if ([dicHead[@"statuscode"] intValue] == 100) {
            NSMutableDictionary *saveDic = [NSMutableDictionary dictionary];
            [saveDic setObject:dicBody[@"userid"] forKey:@"userid"];
            [saveDic setObject:dicBody[@"avatar"] forKey:@"avatar"];
            [saveDic setObject:dicBody[@"account"] forKey:@"account"];
            [saveDic setObject:dicBody[@"nickname"] forKey:@"nickname"];
            [saveDic setObject:self.SESSID forKey:@"SESSID"];
            [saveDic setObject:dicBody[@"hostdate"] forKey:@"hostdate"];
            [saveDic setObject:@"13004798971" forKey:@"phoneNum"];
            [saveDic setObject:@"666666" forKey:@"password"];
            //         NSLog(@"登录：%@",dict);
            [self showCustomAlertMessage:@"登录成功"];
            
            [[NSUserDefaults standardUserDefaults]setObject:@"666666" forKey:@"password"];
//            //登录成功后保存账号和密码
            [[NSUserDefaults standardUserDefaults]setObject:@"13004798971" forKey:@"account"];
            [[NSUserDefaults standardUserDefaults]setObject:@"666666" forKey:@"psd"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [WKLoginHandel saveLoginDataWithDict:saveDic.mutableCopy];
            //登录成功
            WKHomeViewController *mainVC = [[WKHomeViewController alloc] init];
            mainVC.userId = dicBody[@"userid"];
            WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:mainVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
        }else if ([dicHead[@"statuscode"] intValue] == 998){
            
        }else{
            
            [weakSelf showCustomAlertMessage:@"账号或密码错误"];
        }
        
    }];
}
#pragma mark - 直接登录
- (IBAction)loginAction:(UIButton *)sender {
    
    [MobClick profileSignInWithPUID:@"login_onclick"];//启动友盟账号统计
    __weak typeof(self) weakSelf = self;

    NSString * callBackStr = [WKUniversal validateMobile:self.TFPhoneNum.text];
    if (callBackStr) {
        [self showCustomAlertMessage:callBackStr];
        return;
    }
    if (StringIsNullOrEmpty(self.TFPassword.text)) {

        [self showCustomAlertMessage:@"请输入密码"];
        return;
    }
    if ([self.TFPassword.text length]<6 || [self.TFPassword.text length]>18) {
        [self showCustomAlertMessage:@"密码长度不合法"];
    
        return;
    }
    _reachabilityStatus = [AppDelegate shareDelegate].reachabilityStatus;
    if (_reachabilityStatus == 0) {
        self.alertView = [[WKAlerView alloc]initWithFrame:[UIScreen mainScreen].bounds message:@"当前网络未连接!" tip:@"" title1:@"退出应用" title2:@"离线模式"];
        self.alertView.isPlayer = YES;
        self.alertView.confirmBlock = ^{
            exit(0);
        };
        self.alertView.cancelBlock = ^{
            
            WKDownLoadViewController *downloadVc = [[WKDownLoadViewController alloc]init];
            [weakSelf.navigationController pushViewController:downloadVc animated:YES];
            [weakSelf.alertView removeFromSuperview];
        };
        self.alertView.deleteBlock = ^{
                        [weakSelf.alertView removeFromSuperview];
        };
        [[UIApplication sharedApplication].keyWindow addSubview:self.alertView];
        return;
    }
    NSDate *date = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMddhhmmss"];
    NSString *timestamp = [dateformatter stringFromDate:date];
    
    NSString *deviceID = mydeviceUniqueIdentifier();
    NSString *version =[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSString *mac= [WKUniversal macaddress];
    //13500000001
    //111111
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:self.TFPhoneNum.text forKey:@"account"];
    [para setObject:self.TFPassword.text forKey:@"password"];
    [para setObject:timestamp   forKey:@"timestamp"];
    [para setObject:@"1" forKey:@"sequenceid"];
    [para setObject:@"login" forKey:@"commandid"];
    [para setObject:version forKey:@"version"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:deviceID forKey:@"deviceid"];
    NSLog(@"登录mac：%@",mac);
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"登录中..." completionHandler:^(id responseObject) {
        
       
    } errorHandler:^(NSError *error) {
    
        [weakSelf showCustomAlertMessage:@"网络错误"];
        
    } finishHandler:^(id responseObject) {
       
        NSArray * cookieArr = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];//获取cookie
        for (NSHTTPCookie * cookie in cookieArr) {          //遍历cookie
            if ([cookie.name isEqualToString:@"PHPSESSID"]) {
                self.SESSID = cookie.value;
            }
        }
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *dicBody = dict[@"body"];
        NSDictionary *dicHead = dict[@"head"];
        NSLog(@"登录接口：%@",dict);
        if ([dicHead[@"statuscode"] intValue] == 100) {
            
            NSMutableDictionary *saveDic = [NSMutableDictionary dictionary];
            [saveDic setObject:dicBody[@"userid"] forKey:@"userid"];
            [saveDic setObject:dicBody[@"avatar"] forKey:@"avatar"];
            [saveDic setObject:dicBody[@"account"] forKey:@"account"];
            [saveDic setObject:dicBody[@"nickname"] forKey:@"nickname"];
            [saveDic setObject:self.SESSID forKey:@"SESSID"];
            [saveDic setObject:dicBody[@"hostdate"] forKey:@"hostdate"];
            [saveDic setObject:self.TFPhoneNum.text forKey:@"phoneNum"];
            [saveDic setObject:self.TFPassword.text forKey:@"password"];
            //         NSLog(@"登录：%@",dict);
            [self showCustomAlertMessage:@"登录成功"];
            [[NSUserDefaults standardUserDefaults]setObject:self.TFPassword.text forKey:@"password"];
            //登录成功后保存账号和密码
            [[NSUserDefaults standardUserDefaults]setObject:self.TFPhoneNum.text forKey:@"account"];
            [[NSUserDefaults standardUserDefaults]setObject:self.TFPassword.text forKey:@"psd"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [WKLoginHandel saveLoginDataWithDict:saveDic.mutableCopy];
            //登录成功
            WKHomeViewController *mainVC = [[WKHomeViewController alloc] init];
            mainVC.userId = dicBody[@"userid"];
            WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:mainVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
        }else if ([dicHead[@"statuscode"] intValue] == 998){
            //登录出现错误 跳转到忘记密码页面
            WKVerifyPhoneViewController *verifyVC  = [[WKVerifyPhoneViewController alloc]init];
            [self.navigationController pushViewController:verifyVC animated:YES];
        }else{
            
            [weakSelf showCustomAlertMessage:@"账号或密码错误"];
        }
        
    }];
}
 
#pragma mark - qq登录
- (IBAction)qqLoginAction:(UIButton *)sender {

    [MobClick profileSignInWithPUID:@"qqlogin_onclick"];
    NSArray *permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_INFO, kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, nil];
    // 这里调起登录
    [_tencentOAuth authorize:permissions inSafari:NO];
    
}
//登录成功：
- (void)tencentDidLogin{
    
    if (_tencentOAuth.accessToken.length > 0) {
        // 获取用户信息
        [_tencentOAuth getUserInfo];
        NSLog(@"qq用户记录：%@",_tencentOAuth.passData);
    } else {
        NSLog(@"登录不成功 没有获取accesstoken");
    }
}
//非网络错误导致登录失败：
- (void)tencentDidNotLogin:(BOOL)cancelled {
    
    if (cancelled) {
        NSLog(@"用户取消登录");
        [self showCustomAlertMessage:@"您已取消QQ登录"];
    } else {
        NSLog(@"登录失败");
        [self showCustomAlertMessage:@"QQ登录失败"];
    }
}
// 获取用户信息
- (void)getUserInfoResponse:(APIResponse *)response {
    
    if (response && response.retCode == URLREQUEST_SUCCEED) {
        
        NSDictionary *userInfo = [response jsonResponse];
        NSLog(@"qq用户信息%@",userInfo);
        //走三方登录接口
        [self bangdingAccountWithOpenid:_tencentOAuth.openId site:@"qzone" nickName:userInfo[@"nickname"]];
        // 后续操作...
    } else {
        NSLog(@"QQ auth fail ,getUserInfoResponse:%d", response.detailRetCode);
    }
}
- (BOOL)tencentNeedPerformIncrAuth:(TencentOAuth *)tencentOAuth
                   withPermissions:(NSArray *)permissions {
    // incrAuthWithPermissions是增量授权时需要调用的登录接口
    // permissions是需要增量授权的权限列表
    [tencentOAuth incrAuthWithPermissions:permissions];
    return YES; // 返回NO表明不需要再回传未授权API接口的原始请求结果；
    // 否则可以返回YES
}
- (void)tencentDidNotNetWork{
    
    
}
#pragma mark - 微信登录
- (IBAction)weChatLoginAction:(UIButton *)sender {
    [MobClick profileSignInWithPUID:@"weixin_onclick"];
    if ([WXApi isWXAppInstalled]) {
        //构造SendAuthReq结构体
        SendAuthReq* req =[[SendAuthReq alloc ] init ];
        req.scope = kWxScope ;
        req.state = kWxState ;
        NSString *tmpOpenId = [[NSUserDefaults standardUserDefaults] objectForKey:@"openid"];
        req.openID = tmpOpenId;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
        
    }else{
        
        [self showCustomAlertMessage:@"您尚未安装微信"];
    }
}
#pragma mark - 微信登录成功
- (void)weChatLoginSuccess:(NSNotification *)notifi{
    
    __weak typeof(self) weakSelf = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"https://api.weixin.qq.com/sns/oauth2/access_token" parameters:@{@"appid":kWxAppID, @"secret":kWxAppSecret, @"code":notifi.object[@"code"], @"grant_type":@"authorization_code"} progress:^(NSProgress * _Nonnull downloadProgress){
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"WXSaveToken"];
        NSLog(@"微信登录成功：%@",dict);
        [weakSelf saveTokenAndRequireWXInfo];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"access_token error-->%@", error.localizedDescription);
    }];
}
- (void)saveTokenAndRequireWXInfo{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:@"WXSaveToken"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"https://api.weixin.qq.com/sns/userinfo" parameters:@{@"openid":dict[@"openid"], @"access_token":dict[@"access_token"]} progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                NSLog(@"微信保存用户信息%@",dict);
        [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"openid"];
        [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"WXResponse_UserInfo"];
        //走三方登录接口
        [weakSelf bangdingAccountWithOpenid:dict[@"unionid"] site:@"weixin" nickName:dict[@"nickname"]];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"userinfo error-->%@", error.localizedDescription);
    }];
}
#pragma mark - 第三方登录接口
- (void)bangdingAccountWithOpenid:(NSString*)openid site:(NSString*)site nickName:(NSString*)nickName{
    
    [MobClick profileSignInWithPUID:@"playerID" provider:@"WeChat"];
    NSString *version =[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"openlogin" forKey:@"commandid"];
    [para setObject:openid forKey:@"openid"];
    [para setObject:site forKey:@"site"];
    [para setObject:[WKUniversal macaddress] forKey:@"mac"];
    [para setObject:version forKey:@"version"];
    NSLog(@"参数%@",para);
    __weak typeof(self) weakSelf = self;
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"登录中..." completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        NSLog(@"userinfo error-->%@", error.localizedDescription);
        [weakSelf showCustomAlertMessage:@"网络连接错误"];
        
    } finishHandler:^(id responseObject) {
        NSArray * cookieArr = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];//获取cookie
        for (NSHTTPCookie * cookie in cookieArr) {          //遍历cookie
            if ([cookie.name isEqualToString:@"PHPSESSID"]) {
                self.SESSID = cookie.value;
            }
        }
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSLog(@"weChat登录：%@",dict);
        NSDictionary *headDict = dict[@"head"];
        NSDictionary *bodyDict = dict[@"body"];
        NSString *statuscode =headDict[@"statuscode"];
        NSLog(@"三方登录返回值：%@",statuscode);
        if ([statuscode intValue] == 999) {
            //请关联或注册帐号
            WKBindingViewController *bindingVC = [[WKBindingViewController alloc]init];
            bindingVC.openid = openid;
            bindingVC.site = site;
            bindingVC.nickName = nickName;
            [self.navigationController pushViewController:bindingVC animated:YES];
            
        }else if ([statuscode intValue] == 100){
            //直接登录
            NSMutableDictionary *saveDic = [NSMutableDictionary dictionary];
            [saveDic setObject:bodyDict[@"userid"] forKey:@"userid"];
            [saveDic setObject:bodyDict[@"avatar"] forKey:@"avatar"];
            [saveDic setObject:bodyDict[@"account"] forKey:@"account"];
            [saveDic setObject:bodyDict[@"nickname"] forKey:@"nickname"];
            [saveDic setObject:self.SESSID forKey:@"SESSID"];
            [saveDic setObject:bodyDict[@"hostdate"] forKey:@"hostdate"];
             [WKLoginHandel saveLoginDataWithDict:saveDic.mutableCopy];
            //绑定成功
            NSString *userid = bodyDict[@"userid"];
            WKHomeViewController *mainVC = [[WKHomeViewController alloc] init];
            mainVC.userId = userid;
            WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:mainVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
        }
    }];
}
#pragma mark - 忘记密码
- (IBAction)forgetPasswordAction:(UIButton *)sender {
    [MobClick profileSignInWithPUID:@"forgetpwd_onclick"];
    WKForgetPasswordController *verifyVC = [[WKForgetPasswordController alloc]init];
    
    [self.navigationController pushViewController:verifyVC animated:YES];
    
}
#pragma mark - 注册
- (IBAction)registAction:(UIButton *)sender {
    [MobClick profileSignInWithPUID:@"register_onclick"];
    WKRegistViewController *registVC = [[WKRegistViewController alloc]init];
    
    [self.navigationController pushViewController:registVC animated:YES];
    
}
#pragma mark - 键盘抬起
- (void)keyBoardWillShow:(NSNotification*)nofi{
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.logoViewConstan.constant = 44;
    }];
    
}
#pragma mark - 键盘回收
- (void)keyBoardWillHiden:(NSNotification*)nofi{
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.logoViewConstan.constant = 64;
    }];
    
}
- (void)dealloc{
     [[AppDelegate shareDelegate] removeObserver:self forKeyPath:@"reachabilityStatus"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
//    if (_isOnLine) {
//        self.btnTourists.hidden = NO;
//        self.labelTourists.hidden = NO;
//        self.btnTourists.frame = CGRectMake(((kDeviceScreenWidth - 40*2-70*2)-70)*0.5+40+70, self.BtnQQ.top, 70, 70);
//        self.labelTourists.frame = CGRectMake(((kDeviceScreenWidth - 40*2-70*2)-70)*0.5+40+70, CGRectGetMaxY(self.btnTourists.frame)+7, 70, 21);
//    }else{
//        self.remberLabel.text = @"第三方登录";
//        self.BtnQQ.frame = CGRectMake(80, CGRectGetMaxY(self.remberLabel.frame)+15, 70, 70);
//        self.labelQQ.frame = CGRectMake(80, CGRectGetMaxY(self.BtnQQ.frame)+15, 70, 21);
//        self.btnTourists.hidden = YES;
//        self.labelTourists.hidden = YES;
//        self.BtnWeChat.frame = CGRectMake(kDeviceScreenWidth-80-70, CGRectGetMaxY(self.remberLabel.frame)+15, 70, 70);
//        self.weixinLabel.frame = CGRectMake(kDeviceScreenWidth-80-70, CGRectGetMaxY(self.BtnWeChat.frame)+15, 70, 21);
//    }
//    if (_isOnLine) {
//        self.btnTourists.frame = CGRectMake(((kDeviceScreenWidth - 40*2-70*2)-70)*0.5+40+70, self.BtnQQ.top, 70, 70);
//        self.labelTourists.frame = CGRectMake(((kDeviceScreenWidth - 40*2-70*2)-70)*0.5+40+70, CGRectGetMaxY(self.btnTourists.frame)+7, 70, 21);
//    }else{
//        self.remberLabel.text = @"第三方登录";
//        self.BtnQQ.frame = CGRectMake(80, CGRectGetMaxY(self.remberLabel.frame)+15, 70, 70);
//        self.labelQQ.frame = CGRectMake(80, CGRectGetMaxY(self.BtnQQ.frame)+15, 70, 21);
//        self.BtnWeChat.frame = CGRectMake(kDeviceScreenWidth-80-70, CGRectGetMaxY(self.remberLabel.frame)+15, 70, 70);
//        self.weixinLabel.frame = CGRectMake(kDeviceScreenWidth-80-70, CGRectGetMaxY(self.BtnWeChat.frame)+15, 70, 21);
//    }
    
    if (iPhone5) {
       
        self.ImgLogoView.frame = CGRectMake((kDeviceScreenWidth-115)*0.5, 64, 115, 115);
        self.TFPhoneNum.top = CGRectGetMaxY(self.ImgLogoView.frame) + 20;
        self.TFPassword.top = CGRectGetMaxY(self.TFPhoneNum.frame) + 20;
        self.BtnLogin.top = CGRectGetMaxY(self.TFPassword.frame) + 20;
        self.BtnForgetPsd.top = CGRectGetMaxY(self.BtnLogin.frame) + 10;
        self.BtnRegist.top = CGRectGetMaxY(self.BtnLogin.frame) + 10;
        self.BtnQQ.top = CGRectGetMaxY(self.remberLabel.frame)+5;
        self.labelQQ.top = CGRectGetMaxY(self.BtnQQ.frame)+5;
        self.btnTourists.top = CGRectGetMaxY(self.remberLabel.frame)+5;
        self.labelTourists.top = CGRectGetMaxY(self.btnTourists.frame)+5;
        self.BtnWeChat.top = CGRectGetMaxY(self.remberLabel.frame)+5;
        self.weixinLabel.top = CGRectGetMaxY(self.BtnWeChat.frame)+5;
//        self.BtnQQTopConstan.constant = 5;
//        self.BtnWeChatTopConstan.constant = 5;
//        self.BtnQQConstan.constant = 60;
//        self.BtnWeChatConstan.constant = 60;
//        self.leftLineConstan.constant = 10;
//        self.rightLineConstan.constant = 10;
        
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
